package com.gary.shiro.config.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class ShiroSessionDAO extends AbstractSessionDAO {

    @Autowired
    private RedisTemplate<String,Object> shiroRedisTemplate;

    private static final String SESSION_KEY = "gary.shiro.session";

    private static final Long SESSION_TIMEOUT = 30*60*1000L;
    
    //创建session时 将session存到redis 并设置过期时间
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        session.setTimeout(SESSION_TIMEOUT);

        shiroRedisTemplate.opsForHash().put(SESSION_KEY, sessionId, session);
        shiroRedisTemplate.expire(SESSION_KEY, SESSION_TIMEOUT, TimeUnit.MILLISECONDS);
        return sessionId;
    }

    //读取session的时候 先从redis中读 如果没有返回空
    @Override
    protected Session doReadSession(Serializable sessionId) {
        if(sessionId == null){
            return null;
        }

        Object session = shiroRedisTemplate.opsForHash().get(SESSION_KEY, sessionId);
        if(session == null){
            return null;
        }
        return (Session) session;
    }

    //更新session的时候
    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session == null || session.getId() == null) {
            return;
        }

        session.setTimeout(SESSION_TIMEOUT);
        shiroRedisTemplate.opsForHash().put(SESSION_KEY, session.getId(), session);
        shiroRedisTemplate.expire(SESSION_KEY, SESSION_TIMEOUT, TimeUnit.MILLISECONDS);
    }
   
    //删除session的时候
    @Override
    public void delete(Session session) {
        if (null == session) {
            return;
        }
        shiroRedisTemplate.opsForHash().delete(SESSION_KEY, session.getId());
    }
    
    //获取所有活跃的session
    @Override
    public Collection<Session> getActiveSessions() {
        List<Object> sessionList = shiroRedisTemplate.opsForHash().values(SESSION_KEY);
        List<Session> list = new ArrayList<>();
        sessionList.forEach(session -> {
            list.add((Session) session);
        });
        return list;
    }
}

